package com.example.system.service.sysuser;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.HttpConstants;
import com.example.common.core.domain.LoginUser;
import com.example.common.core.domain.Result;
import com.example.common.core.domain.vo.LoginUserVO;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.enums.UserIdentity;
import com.example.security.service.TokenService;
import com.example.system.domain.sysuser.SysUser;
import com.example.system.domain.sysuser.dto.SysUserSaveDTO;
import com.example.system.mapper.sysuser.SysUserMapper;
import com.example.system.utils.BCryptUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/1/19 18:57
 */
@Service
@RefreshScope  //确保配置变更后，不需要重启服务
public class SysUserServiceImpl implements SysUserService{


    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;


    //登录
    @Override
    public Result login(String userAccount, String password) {
        //通过账号从数据库中查找用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //select password from tb_sys_user where user_account = #{userAccount};
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName) //在数据库中查字段
                .eq(SysUser::getUserAccount, userAccount));
        Result result = new Result();
        if (sysUser == null){
            result.setCode(ResultCode.FAILED_USER_NOT_EXISTS.getCode());
            result.setMsg("当前登录用户不存在");
            return result;
        }
        if(BCryptUtils.matchesPassword(password,sysUser.getPassword())){
            result.setCode(ResultCode.SUCCESS.getCode());
            result.setMsg("登录成功");
            //生成jwt并存到redis中
            String token = tokenService.createToken(sysUser.getUserId(),secret,UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null);
            result.setData(token);

            return result;
        }
        result.setCode(ResultCode.FAILED_LOGIN.getCode());
        result.setMsg("账号或密码错误");


        return result;
    }


    //从redis中找用户的信息 - 后台管理页面的用户名
    @Override
    public Result info(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        //从redis中获取loginUser
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null){
            return new Result(ResultCode.FAILED.getCode(),"当前用户已过期，请重新登录","");
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return new Result(ResultCode.SUCCESS.getCode(),"获取用户信息成功",loginUserVO);
    }


    //注销登录
    @Override
    public Result logout(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        //从redis中删除键值对
        boolean logout = tokenService.deleteLoginUser(token,secret);
        if (logout){
            return new Result(ResultCode.SUCCESS.getCode(),"注销成功","");
        }
        return new Result(ResultCode.FAILED.getCode(),"注销失败","");
    }




    //添加
    @Override
    public Result add(SysUserSaveDTO sysUserSaveDTO) {


        //从数据库里面查找要添加的用户名是否存在
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        //数据库中是否存在要添加的账号
        if (CollectionUtil.isNotEmpty(sysUserList)){
            //用户已存在
            Result result = new Result(ResultCode.AILED_USER_EXISTS.getCode(),"添加失败，此用户已存在","");
            return result;
        }


        //将dto转成实体
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));

        int insert = sysUserMapper.insert(sysUser);
        Result result = new Result();
        if (insert>0){
            result.setCode(200);
            result.setMsg("Success");
            return result;
        }
        result.setCode(000);
        result.setMsg("添加失败");
        return result;
    }

}












